package com.sgcc.activiti.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.sgcc.activiti.util.HttpsUrlValidator;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.utils.FastJsonUtil;
import com.sgcc.common.core.utils.HttpClientUtil;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sgcc.activiti.mapper.OContentAppPicMapper;
import com.sgcc.activiti.domain.OContentAppPic;
import com.sgcc.activiti.service.IOContentAppPicService;
import sun.misc.BASE64Encoder;

/**
 * 资讯图片Service业务层处理
 *
 * @author sgcc
 * @date 2021-03-31
 */
@Service
public class OContentAppPicServiceImpl implements IOContentAppPicService {
    @Autowired
    private OContentAppPicMapper oContentAppPicMapper;

    /**
     * 查询资讯图片
     *
     * @param id 资讯图片ID
     * @return 资讯图片
     */
    @Override
    public OContentAppPic selectOContentAppPicById(String id) {
        return oContentAppPicMapper.selectOContentAppPicById(id);
    }

    /**
     * 查询资讯图片列表
     *
     * @param oContentAppPic 资讯图片
     * @return 资讯图片
     */
    @Override
    public List<OContentAppPic> selectOContentAppPicList(OContentAppPic oContentAppPic) {
        return oContentAppPicMapper.selectOContentAppPicList(oContentAppPic);
    }

    /**
     * 新增资讯图片
     *
     * @param oContentAppPic 资讯图片
     * @return 结果
     */
    @Override
    public int insertOContentAppPic(OContentAppPic oContentAppPic) {
        return oContentAppPicMapper.insertOContentAppPic(oContentAppPic);
    }

    /**
     * 修改资讯图片
     *
     * @param oContentAppPic 资讯图片
     * @return 结果
     */
    @Override
    public int updateOContentAppPic(OContentAppPic oContentAppPic) {
        return oContentAppPicMapper.updateOContentAppPic(oContentAppPic);
    }

    /**
     * 批量删除资讯图片
     *
     * @param ids 需要删除的资讯图片ID
     * @return 结果
     */
    @Override
    public int deleteOContentAppPicByIds(String[] ids) {
        return oContentAppPicMapper.deleteOContentAppPicByIds(ids);
    }

    /**
     * 删除资讯图片信息
     *
     * @param id 资讯图片ID
     * @return 结果
     */
    @Override
    public int deleteOContentAppPicById(String id) {
        return oContentAppPicMapper.deleteOContentAppPicById(id);
    }

    @Override
    public OContentAppPic uploadImg(OContentAppPic oContentAppPic) throws Exception {
        String url = oContentAppPic.getPicUrl();
        String serviceType = oContentAppPic.getPicType();
        if (StringUtils.isBlank(url)) {
            return oContentAppPic;
        }

//        String uploadImgRpcInterface = DictUtils.getDictValue("上传图片接口", "rpcInterface", "test");
        String uploadImgRpcInterface = "test";
        if ("test".equals(uploadImgRpcInterface)) {
            String appId = "test001";
            //远程系统图片ID
            oContentAppPic.setAppId(appId);
            return oContentAppPic;
        }
        String[] split = url.split("/");
        String fileName = split[split.length - 1];

        // 对字节数组Base64编码
        String encodeData = HttpsUrlValidator.retrieveResponseFromServer(url);
        /**
         * 调用远程图片接口
         * uploadImgRpcInterface
         */
        String params = "";
        //构建参数
        Map paramsData = new HashMap();
        paramsData.put("areaNo", "35101");
        paramsData.put("busiType", "02");
        paramsData.put("contractChannel", "01");
        paramsData.put("fileContent", encodeData);
        paramsData.put("fileName", fileName);
        paramsData.put("serviceType", serviceType);
        paramsData.put("storageBase", "inside");
        ;

        Map map = new HashMap();
        map.put("serviceCode", "0101296");
        map.put("source", "SGAPP");
        map.put("target", "35101");
        map.put("data", paramsData);
        params = FastJsonUtil.toJSONString(map);
        R<String> rpcResultStr = HttpClientUtil.sendJsonStr(uploadImgRpcInterface, params);
        //解析返回值
        if (rpcResultStr.getCode() != 200) {
            return null;
        }
        R r = FastJsonUtil.toBean(rpcResultStr.getData(), R.class);
        int code = r.getCode();
        if (code == 1) {
            JSONObject data = (JSONObject) r.getData();
            //文件ID
            String fileId = data.getString("fileId");
            //文件名称
            String fileName2 =data.getString("fileName");
            //远程系统图片ID
            oContentAppPic.setAppId(fileId);
            return oContentAppPic;
        } else {
            throw new Exception("远程图片上传失败");
        }
    }


    private String getBase64(String url) {
        InputStream in = null;
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        //读取图片字节数组
        try {
            URL url2 = new URL(url);
            final byte[] by = new byte[1024];
            // 创建链接获取图片
            final HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            in = conn.getInputStream();
            int len = -1;
            while ((len = in.read(by)) != -1) {
                data.write(by, 0, len);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //返回Base64编码过的字节数组字符串
        String encode = encoder.encode(data.toByteArray());
//        String[] split = url.split(".");
//        String head = "data:image/" + split[split.length - 1] + ";base64,";
        encode = encode.replaceAll("[\\s*\t\n\r]", "");
        return encode;
    }
}
